<template>
    <div class="user-management-wrapper">
      <div class="top-wrapper">
        <span>角色：</span>

        <el-select v-model="currentRole" size="small" placeholder="请选择">
          <el-option
            v-for="item in selectOptions"
            :label="item.name"
            :value="item.key">
          </el-option>
        </el-select>

        <span style="margin-left: 25px;">姓名：</span>

        <el-autocomplete
          class="inline-input"
          size="small"
          v-model="filterAccountPrefix"
          :fetch-suggestions="fetchQueryUsers"
          placeholder="请输入名字"
          @select="selectQueryUser">
        </el-autocomplete>

        <el-button
          size="small"
          type="info"
          @click="search()">查询</el-button>

        <el-button
          size="small"
          type="info"
          @click="createUser()">添加用户</el-button>
      </div>


        <el-table
          key="xxx"
          v-bind:data="userList"
          border
          stripe
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            prop=""
            width="70"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="头像"
            prop="portrait"
            min-width="80"
            align="center">
            <template scope="scope">
              <img class="portrait" :src="scope.row.portrait">
            </template>
          </el-table-column>
          <el-table-column
            type=""
            label="真实姓名"
            prop="fullName"
            width="130"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="账户名"
            prop="loginAccount"
            min-width="80"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="教龄"
            prop="teachingExperience"
            width="70"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="昵称"
            prop="nickName"
            min-width="80"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="评级"
            prop="rating"
            min-width="80"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="联系邮箱"
            prop="email"
            min-width="80"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="联系电话"
            prop="phone"
            min-width="80"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="创建人"
            prop="creatorFullName"
            min-width="80"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="创建人角色"
            prop="creatorRoleName"
            min-width="80"
            align="center">
          </el-table-column>
          <el-table-column
            type=""
            label="操作"
            prop=""
            min-width="200"
            align="center">
            <template scope="scope">
              <el-button
                size="small"
                @click="modifyInfo(scope.$index, scope.row)">修改信息</el-button>
              <el-button
                size="small"
                @click="modifyPortrait(scope.$index, scope.row)">修改头像</el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteUser(scope.$index, scope.row)">删除</el-button>
              <el-button
                size="small"
                @click="modifyPassword(scope.$index, scope.row)">修改密码</el-button>
            </template>
          </el-table-column>
        </el-table>


      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalSize">
      </el-pagination>

      <el-dialog title="添加用户" v-model="showCreateUserDialog" size="tiny">
        <div>
          <span>选择角色：</span>
          <el-select v-model="createUserDialog.currentRole" @change="selectUserRoleOfCreateUser" size="small" placeholder="请选择">
            <el-option
              v-for="item in createUserDialog.selectOptions"
              :label="item.name"
              :value="item.key">
            </el-option>
          </el-select>
        </div>

        <div style="margin-top: 15px;">
          <span>真实姓名：</span>
          <el-input
            v-model="createUserDialog.realName"
            placeholder="输入真实姓名" max="200"
            class="input-default">
          </el-input>
        </div>

        <div style="margin-top: 15px;">
          <span>用户账户：</span>
          <el-input
            v-model="createUserDialog.loginAccount"
            placeholder="请使用英文字母、数字和_" max="200"
            class="input-default">
          </el-input>
        </div>

        <div style="margin-top: 15px;">
          <span>用户密码：</span>
          <el-input
            v-model="createUserDialog.password"
            placeholder="请输入数字字母的组合" max="200"
            class="input-default">
          </el-input>
        </div>

        <div style="margin-top: 15px;">
          <span>联系邮箱：</span>
          <el-input
            v-model="createUserDialog.email"
            placeholder="例:yiqijiao@163.com" max="200"
            class="input-default">
          </el-input>
        </div>

        <div style="margin-top: 15px;">
          <span>联系电话：</span>
          <el-input
            v-model="createUserDialog.phone"
            placeholder="请输入11位手机号" max="200"
            class="input-default">
          </el-input>
        </div>

        <div style="margin-top: 15px;" v-if="createUserDialog.isSelectedTeacher">
          <span>科目：</span>
          <el-select v-model="createUserDialog.subject" size="small" placeholder="请选择" style="margin-left: 29px;">
            <el-option
              v-for="item in createUserDialog.subjectOptions"
              :label="item.name"
              :value="item.key">
            </el-option>
          </el-select>
        </div>

        <div style="margin-top: 15px;" v-if="createUserDialog.isSelectedTeacher">
          <span>昵称：</span>
          <el-input
            style="margin-left: 29px;"
            v-model="createUserDialog.nickName"
            placeholder="不超过6个字符" max="200"
            class="input-default">
          </el-input>
        </div>

        <div style="margin-top: 15px;" v-if="createUserDialog.isSelectedTeacher">
          <span>教龄：</span>
          <el-input
            style="margin-left: 29px;"
            v-model="createUserDialog.teachAge"
            placeholder="只能输入数字" max="200"
            class="input-default">
          </el-input>
        </div>

        <div style="margin-top: 15px;" v-if="createUserDialog.isSelectedTeacher">
          <span>评级：</span>
          <el-input
            style="margin-left: 29px;"
            v-model="createUserDialog.level"
            placeholder="不能超过30个字" max="200"
            class="input-default">
          </el-input>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="showCreateUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmToCreateUser()">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="提示" v-model="showDeleteUserDialog" size="tiny">
        <span>确定删除{{ currentItem.fullName }}？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDeleteUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmToDeleteUser()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>
<style lang="less">

  .user-management-wrapper{
    margin-top: 60px;
    padding: 15px 10px 0 10px;
    .top-wrapper {
      padding:15px 0 15px 0;
    }
    .portrait{
      width:80px;
    }
    .pagination{
      margin:20px 0 50px 0;
    }
  }
</style>

<script>
  import Item from './UserItem.vue'
  import Pagination from '../common/Pagination.vue'
  import VSelect from '../common/Select.vue'
  import AutoComplete from '../common/AutoComplete.vue'
  export default {
    name: 'userManagement',

    data () {
      return {
        type: 'userManagement',
        searchNamePlaceholder: '请输入名字',
        // userList: this.$store.getters.activeItems || [],
        selectOptions: [],
        currentRole: '',
        currentItem: {},
        filterAccountPrefix: '',
        totalSize: 0,
        loading: false,
        showCreateUserDialog: false,
        showModifyUserInfoDialog: false,
        showDeleteUserDialog: false,
        createUserDialog: {
          isSelectedTeacher: false,
          subjectOptions: [],
          selectOptions: [],
          currentRole: '',
          realName: '',
          loginAccount: '',
          password: '',
          email: '',
          phone: '',
          subject: '',
          nickName: '',
          teachAge: '',
          level: '',
          errorTip: ''
        }
      }
    },

    ready () {
      this.getUserList()
    },

    methods: {
      getUserList (currentPage = this.currentPage) {
        this.$store.dispatch('FETCH_USER_LIST_DATA', {
          role: this.currentRole.replace('ROLE_', ''),
          type: this.type,
          filterAccountPrefix: this.filterAccountPrefix || null
        }).then((response) => {
          this.totalSize = this.$store.state.userManagementStore.totalSize
        })
      },
      getUserRoles (queryOperation) {
        this.$store.dispatch('FETCH_USER_ROLES', { queryOperation: queryOperation })
          .then(response => {
            queryOperation && (this.selectOptions = response.body.result)
            queryOperation || (this.createUserDialog.selectOptions = response.body.result)
          })
      },
      getAllQueryUser () {
        let role = this.currentRole.replace('ROLE_', '') || 'SUPER_ADMIN'
        return this.$store.dispatch('FETCH_QUERY_USER_LIST', { role })
      },
      selectQueryUser (item) {
        console.log(this.filterAccountPrefix)
      },
      fetchQueryUsers (queryString, cb) {
        this.getAllQueryUser()
          .then(response => {
            cb(this.queryUserList.filter((item, index) => {
              item.value = item.fullName + ' | ' + item.loginAccount
              if (item.value.indexOf(queryString) !== -1) {
                return item
              }
            }))
          })
      },
      search () {
        this.getUserList()
      },
      createUser () {
        this.getUserRoles(false)
        this.showCreateUserDialog = true
      },
      modifyInfo (index, row) {

      },
      modifyPortrait (index, row) {

      },
      modifyPassword (index, row) {

      },
      handleCurrentChange (val) {
        let currentPage = Number(val)
        this.currentPage = currentPage
        this.$store.dispatch('CHANGE_CURRENT_PAGE', { currentPage })
        this.getUserList()
      },

      handleSizeChange (val) {
        let pageSize = val
        console.log(val)
        this.$store.dispatch('CHANGE_ITEMS_PER_PAGE', { pageSize })
          .then(response => {
            this.getUserList()
          })
      },

      selectUserRoleOfCreateUser (val) {
        if (val === 'ROLE_PT_TEACHER' || val === '') {
          this.createUserDialog.isSelectedTeacher = true
        } else {
          this.createUserDialog.isSelectedTeacher = false
        }
      },

      confirmToCreateUser () {
        let data = {
          body: {
            fullName: this.createUserDialog.realName,
            loginAccount: this.createUserDialog.loginAccount,
            nickName: this.createUserDialog.nickName || null,
            email: this.createUserDialog.email || null,
            phone: this.createUserDialog.phone || null,
            roleKey: [this.createUserDialog.currentRole],
            creatorFullName: this.$store.state.currentUserFullName,
            creatorRoleName: this.$store.state.currentUserRoleValue,
            portrait: this.createUserDialog.portrait || null,
            portrait_url: this.createUserDialog.portrait_url || null,
            rating: this.createUserDialog.rating || null,
            subjects: [this.createUserDialog.subject],
            teachingExperience: this.createUserDialog.teachAge || null
          },
          loginPassword: this.createUserDialog.password
        }
        this.$store.dispatch('CREATE_USER', data)
          .then(response => {
            this.clearCreatedUserInfo()
            this.getUserList()
            this.showCreateUserDialog = false
          }, response => {
            this.createUserDialog.errorTip = response.message
          })
      },
      clearCreatedUserInfo () {
        Object.keys(this.createUserDialog).forEach(key => {
          if (typeof this.createUserDialog[key] === 'string') {
            this.createUserDialog[key] = ''
            return
          }
          if (typeof this.createUserDialog[key] === 'number') {
            this.createUserDialog[key] = 0
            return
          }
          if (this.createUserDialog[key] instanceof Array) {
            this.createUserDialog[key] = []
            return
          }
          if (this.createUserDialog[key] instanceof Object) {
            this.createUserDialog[key] = {}
          }
        })
      },
      deleteUser (index, row) {
        this.currentItem = row
        this.showDeleteUserDialog = true
      },
      confirmToDeleteUser () {
        this.$store.dispatch('DELETE_USER', this.currentItem)
          .then(response => {
            this.showDeleteUserDialog = false
            this.getUserList()
          }, response => {

          })
      }
    },

    components: {
      Item,
      Pagination,
      VSelect,
      AutoComplete
    },

    computed: {
      currentPage () {
        return Number(this.$store.state.userManagementStore.currentPage) || 1
      },
      pageSize () {
        return this.$store.state.userManagementStore.itemsPerPage
      },
      totalPage () {

      },
      userList () {
        return this.$store.state.userManagementStore.lists
      },
      queryUserList () {
        return this.$store.state.userManagementStore.queryUserList
      }
    },

    watch: {
      currentPage () {
        this.getUserList()
      }
    },
    mounted () {
      this.getUserRoles(true)
      this.getUserList()
    },
    beforeMount () {

    },
    updated () {

    }
  }
</script>

